﻿<%@ WebHandler Language="C#" Class="detail" %>
using System;
using System.Web;
using Newtonsoft.Json;
using System.IO;
using System.Net;
using Newtonsoft.Json.Linq;
using System.Web.Configuration;
using Models;
using System.Linq;
using Common.Helper;


public class detail : IHttpHandler {


    public static string APPID =WebConfigurationManager.AppSettings["APPID"];
    public static string APPSECRET =WebConfigurationManager.AppSettings["APPSECRET"];
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";

        var js_code=HttpContext.Current.Request.QueryString["code"];

        if (string.IsNullOrEmpty(js_code))
        {
            HttpContext.Current.Response.Write("parameter error");
            return;
        }

            string url = string.Format("https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code", APPID, APPSECRET, js_code);
            string json = HttpHelper.GetHtml(url);

           var mybacktoken = JObject.Parse(json);
        
           var authtoken=mybacktoken["openid"].ToString();
           var access_token=mybacktoken["session_key"].ToString();
  


        var code=0;
        using (Entities bll = new Entities())
        {
            var wxuser = bll.User.FirstOrDefault(p => p.UOpenID == authtoken);
            if (wxuser==null) //没有这个用户
            {
                wxuser = new User();
                wxuser.UGuid = _rky.GenerateStringID();
                wxuser.UOpenID = authtoken;
                wxuser.Ustate = 0;
                wxuser.Ujifen = 0;
                wxuser.RegTime = DateTime.Now;
                wxuser.isMember = 0;  //直
                bll.User.Add(wxuser);
                bll.SaveChanges();
            }
            var data = new
            {
                userinfo=wxuser,
                data=new{access_token,user_id=authtoken},
                code,
                msg = "获取session_key",
                time = DateTime.Now
            };

        Formatting microsoftDataFormatSettings = default(Formatting);
        string result = JsonConvert.SerializeObject(data, microsoftDataFormatSettings);

        context.Response.Write(result);

    }

    HttpContext.Current.Response.End();
        //context.Response.Write("Hello World");


    }





public bool IsReusable {
    get {
        return false;
    }
}

}